package me.siphone.view.grouptree;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.hjq.http.EasyHttp;
import com.hjq.http.config.IRequestApi;
import com.hjq.http.listener.HttpCallbackProxy;
import com.hjq.http.listener.OnHttpListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import me.siphone.http.api.QueryGroupApi;
import me.siphone.http.model.HttpData;
import org.linphone.R;

public class GroupTreeFragment extends Fragment implements OnHttpListener<Object> {

    private View view;
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView rvDevice;
    private RecyclerView rvGroup;
    private TextView tvTotalSelectedCount;
    private List<Group> groupList;
    private final Timer timer = new Timer();
    private int selectedCount = 0;

    @Nullable
    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater,
            @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_group_tree, container, false);

        refreshLayout = view.findViewById(R.id.refresher);
        rvDevice = view.findViewById(R.id.device);
        rvGroup = view.findViewById(R.id.group);
        tvTotalSelectedCount = view.findViewById(R.id.tv_total_selected_count);

        refreshLayout.setOnRefreshListener(
                new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        queryGroup();
                    }
                });

        queryGroup();

        startTimer();

        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    private void startTimer() {
        timer.schedule(
                new TimerTask() {
                    @Override
                    public void run() {
                        if (isResumed() && selectedCount == 0) {
                            queryGroup();
                        }
                    }
                },
                10 * 60 * 1000,
                10 * 60 * 1000);
    }

    private void queryGroup() {
        EasyHttp.get(this)
                .api(new QueryGroupApi())
                .request(
                        new HttpCallbackProxy<HttpData<List<QueryGroupApi.DeptObj>>>(this) {
                            @Override
                            public void onHttpSuccess(
                                    @NonNull HttpData<List<QueryGroupApi.DeptObj>> result) {
                                super.onHttpSuccess(result);
                                List<Group> groupList = new ArrayList<>();
                                if (result.getCode() == 200 && result.getData() != null) {
                                    List<QueryGroupApi.DeptObj> deptList = result.getData();
                                    for (QueryGroupApi.DeptObj dept : deptList) {
                                        List<Device> deviceList = new ArrayList<>();
                                        for (QueryGroupApi.DeptObj.Device device :
                                                dept.getDeviceList()) {
                                            deviceList.add(
                                                    new Device(
                                                            device.getId(),
                                                            device.getDeviceName(),
                                                            device.getDeviceUid(),
                                                            device.getOnlineStatus() == 1));
                                        }
                                        Group group =
                                                new Group(
                                                        dept.getDept().getDeptId(),
                                                        dept.getDept().getDeptName(),
                                                        deviceList);
                                        groupList.add(group);
                                    }
                                }
                                initGroupView(groupList);
                            }

                            @Override
                            public void onHttpEnd(@NonNull IRequestApi api) {
                                super.onHttpEnd(api);
                                refreshLayout.setRefreshing(false);
                            }
                        });
    }

    private void initGroupView(List<Group> groupList) {
        this.groupList = groupList;

        rvDevice.setLayoutManager(
                new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));

        rvGroup.addItemDecoration(
                new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        rvGroup.setLayoutManager(
                new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        rvGroup.getItemAnimator().setChangeDuration(0);
        rvGroup.setAdapter(
                new GroupAdapter(
                        groupList,
                        new GroupAdapter.OnSelectionChangedListener() {
                            @Override
                            public void onGroupClick(Group group) {
                                DeviceAdapter deviceAdapter =
                                        new DeviceAdapter(
                                                group.devices,
                                                device -> {
                                                    List<Device> selectedDeviceList =
                                                            getSelectedDeviceList();
                                                    updateSelectedCount(selectedDeviceList.size());
                                                });

                                rvDevice.setAdapter(deviceAdapter);
                            }

                            @Override
                            public void onGroupCheck(Group group) {
                                for (Device device : group.devices) {
                                    if (device.isActive) {
                                        device.isChecked = group.isChecked;
                                    } else {
                                        device.isChecked = false;
                                    }
                                }
                                rvDevice.getAdapter().notifyDataSetChanged();

                                List<Device> selectedDeviceList = getSelectedDeviceList();
                                updateSelectedCount(selectedDeviceList.size());
                            }
                        }));

        if (!groupList.isEmpty()) {
            DeviceAdapter deviceAdapter =
                    new DeviceAdapter(
                            groupList.get(0).devices,
                            new DeviceAdapter.DeviceCheckedChangedListener() {
                                @Override
                                public void onDeviceCheckedChanged(Device device) {
                                    List<Device> selectedDeviceList = getSelectedDeviceList();
                                    updateSelectedCount(selectedDeviceList.size());
                                }
                            });
            rvDevice.setAdapter(deviceAdapter);
        }

        updateSelectedCount(0);
    }

    private void updateSelectedCount(int count) {
        selectedCount = count;
        tvTotalSelectedCount.setText(String.format("已选择%d个设备", count));
    }

    @Override
    public void onHttpSuccess(@NonNull Object result) {}

    @Override
    public void onHttpFail(@NonNull Throwable throwable) {}

    public List<Device> getSelectedDeviceList() {
        List<Device> devices = new ArrayList<>();
        if (this.groupList != null) {
            for (Group group : groupList) {
                for (Device device : group.devices) {
                    if (device.isChecked) {
                        devices.add(device);
                    }
                }
            }
        }
        return devices;
    }

    public void clearSelected() {
        for (Group group : groupList) {
            group.isChecked = false;
            for (Device device : group.devices) {
                device.isChecked = false;
            }
        }
        rvGroup.getAdapter().notifyDataSetChanged();
        rvDevice.getAdapter().notifyDataSetChanged();
    }
}
